import 'package:dio/dio.dart';
import '../request/hi_base_request.dart';
import '../request/hi_http_method.dart';
import 'hi_error.dart';
import 'hi_net_adaper.dart';

class DioAdapter extends HiNetAdapter {
  @override
  Future<HiNetResponse<T>> send<T>(HiBaseRequest request) async {
    var dio = Dio();
    //日志拦截器
    dio.interceptors.add(LogInterceptor());
    // // 设置代理
    // (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
    //     (HttpClient client) {
    //   client.findProxy = (uri) {
    //     return "PROXY 192.168.31.84:8888"; // Charles的代理地址和端口
    //   };
    //   client.badCertificateCallback =
    //       (X509Certificate cert, String host, int port) => true;
    //   return null;
    // };
    //
    // dio.httpClientAdapter = IOHttpClientAdapter(createHttpClient: () {
    //   var httpClient = HttpClient();
    //   httpClient.findProxy = (uri) {
    //     return "PROXY 192.168.31.84:8888";
    //   };
    //   return httpClient;
    // });

    var option = Options(headers: request.header);
    Response? response;
    DioException? error;
    try {
      if (request.httpMethod() == HttpMethod.GET) {
        response = await dio.get(request.url(), options: option);
      } else if (request.httpMethod() == HttpMethod.POST) {
        response = await dio.post(request.url(),
            data: request.params, options: option);
      } else if (request.httpMethod() == HttpMethod.DELETE) {
        response = await dio.delete(request.url(),
            data: request.params, options: option);
      }
    } on DioException catch (e) {
      error = e;
    }

    if (error != null) {
      response = error.response;
      throw HiNetError(response?.statusCode ?? -1, error.message!,
          data: await buildRes(response, request));
    }
    return buildRes(response, request);
  }

  //构建HiNetResponse
  Future<HiNetResponse<T>> buildRes<T>(
      Response? response, HiBaseRequest request) {
    return Future.value(HiNetResponse(
        data: response?.data,
        request: request,
        statusCode: response?.statusCode,
        statusMessage: response?.statusMessage,
        extra: response));
  }
}
